#include "WidgetTextField.h"
#include "RessourceManager.h"

#include <sstream>

WidgetTextField::WidgetTextField(int x, int y, int w, int h) : Widget(x,y)
{
    this->w = w;
    this->h = h;

    this->box.setPosition(x,y);
    this->box.setSize(sf::Vector2f(w,h));

    this->text.setPosition(x,y);
    this->text.setColor(sf::Color(255,255,255,255));
    this->text.setFont(*RessourceManager::getFont("font.ttf"));
    this->text.setCharacterSize(h*4/5);

    this->hasFocus = false;
    this->numeric = false;

    updateGfx();
}

void WidgetTextField::setNumeric(bool b)
{
    numeric = b;
}

void WidgetTextField::onEvent(sf::Event* event)
{
    if(event->type == sf::Event::MouseButtonPressed && event->mouseButton.button == sf::Mouse::Button::Left)
    {
        int mX = event->mouseButton.x;
        int mY = event->mouseButton.y;
        if(mX > x && mX < x+w && mY > y && mY < y+h)
        {
            if(!hasFocus)
            {
                hasFocus = true;
                updateGfx();
            }
        }
        else
        {
            if(hasFocus)
            {
                hasFocus = false;
                updateGfx();
            }
        }
    }

    if(hasFocus && event->type == sf::Event::TextEntered)
    {
        int c = event->text.unicode;
        std::string s = text.getString();
        if(c < 127)
        {
            if(c == 8)
            {
                s = s.substr(0, s.size()-1);
                text.setString(s);
            }
            else if(numeric)
            {
                if(c >= '0' && c <= '9')
                {
                    s += c;
                    text.setString(s);
                }
            }
            else
            {
                if(c >= 32)
                {
                    s += c;
                    text.setString(s);
                }
            }
        }
    }
}

void WidgetTextField::onRender(sf::RenderWindow* window)
{
    window->draw(box);
    window->draw(text);
}

void WidgetTextField::updateGfx()
{
    if(!hasFocus)
    {
        this->box.setFillColor(sf::Color(0,0,0,150));
    }
    else
    {
        this->box.setFillColor(sf::Color(0,0,0,255));
    }
}

std::string WidgetTextField::getText()
{
    return text.getString();
}

int WidgetTextField::getInt()
{
    int i;
    std::stringstream(text.getString()) >> i;
    return i;
}

WidgetTextField::~WidgetTextField()
{

}
